package com.eyas.im.client;

import com.eyas.im.client.nio.NIOIMClient;
import com.eyas.im.client.nio.handler.ConsoleSocketClientHandler;
import com.eyas.im.protocol.decoder.StringDecoder;
import com.eyas.im.protocol.encoder.StringEncoder;
import com.eyas.im.protocol.protocol.StringProtocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class SocketClientTest1 {
    public static void main(String[] args) throws InterruptedException {
        ConsoleSocketClientHandler consoleSocketClientHandler = new ConsoleSocketClientHandler(new StringEncoder(),new StringDecoder(),1024);
        IMClient imClient = new NIOIMClient(consoleSocketClientHandler);
        Thread imClientThread = clientThread(imClient);
        imClientThread.start();
        Runtime.getRuntime().addShutdownHook(new Thread(imClient::shutdwonGraceful));
        consoleSocketClientHandler.sync();
        InputStream inputStream = System.in;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        String lineStr = null;
        System.err.print("请输入>>>:");
        try {
            while (!(lineStr = bufferedReader.readLine()).equals("bye")) {
                TaskCompleteFuture future = consoleSocketClientHandler.write(new StringProtocol(lineStr+"\n"),(e)->{
                    if(e!=null)
                        System.err.println("写入失败:"+e.getLocalizedMessage());
                    else
                        System.err.println("写入成功");
                });
                consoleSocketClientHandler.flush();
//                future.sync();
                System.out.println();
                System.err.print("请输入>>>:");
            }
            System.out.println("byebye");
            consoleSocketClientHandler.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Thread clientThread(IMClient imClient) {
        return new Thread(() -> {
            try {
                imClient.connect("localhost",8888);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
